<template>
    <el-card class="box-card">
        <template #header>
            <div class="card-header">
                <span>编辑商品</span>
            </div>
        </template>
        <el-form label-width="100px">
            <el-form-item label="发布商品">
                <el-space>
                    <el-select @change="handleCateChange(form.cate_1st,0)" v-model="form.cate_1st"
                        placeholder="请选择一级分类">
                        <el-option v-for="(item,index) in cate_1st" :key="item.id" :label="item.name"
                            :value="item.id" />
                    </el-select>
                    <el-select @change="handleCateChange(form.cate_2nd,1)" v-model="form.cate_2nd"
                        placeholder="请选择二级分类">
                        <el-option v-for="(item,index) in cate_2nd" :key="item.id" :label="item.name"
                            :value="item.id" />
                    </el-select>
                    <el-select v-model="form.cate_3rd" placeholder="请选择三级分类">
                        <el-option v-for="(item,index) in cate_3rd" :key="item.id" :label="item.name"
                            :value="item.id" />
                    </el-select>
                </el-space>
            </el-form-item>
            <el-form-item label="商品名称">
                <el-input v-model="form.name"></el-input>
                <el-alert type="info" :closable="false" style="background-color:#fff;padding:0;line-height:24px;">
                    <p>商品标题名称长度至少3个字符，最长200个汉字</p>
                </el-alert>
            </el-form-item>
            <el-form-item label="商品卖点" prop="desc">
                <el-input type="textarea" v-model="form.hotPoint" />
                <el-alert type="info" :closable="false" style="background-color:#fff;padding:0;line-height: 24px;">
                    <p>商品卖点不能超过140个汉字</p>
                </el-alert>
            </el-form-item>
            <el-form-item label="商品价格" prop="desc">
                <div class="mt-4">
                    <el-input v-model="form.price" type="number">
                        <template #append>元</template>
                    </el-input>
                    <el-alert type="info" :closable="false" style="background-color:#fff;padding:0;line-height:24px;">
                        <p>价格必须是0-999999之间的数字，且不能高于市场价</p>
                        <p>此价格为商品实际销售价格，如果商品存在规格，改价格显示最低价格</p>
                    </el-alert>
                </div>
            </el-form-item>
            <el-form-item label="市场价" prop="desc">
                <div class="mt-4">
                    <el-input v-model="form.marketPrice" type="number">
                        <template #append>元</template>
                    </el-input>
                    <el-alert type="info" :closable="false" style="background-color:#fff;padding:0;line-height: 24px;">
                        <p>价格必须是0-999999之间的数字，此价格仅为市场参考价，请根据实际情况认真填写</p>
                    </el-alert>
                </div>
            </el-form-item>
            <el-form-item label="成本价" prop="desc">
                <div class="mt-4">
                    <el-input v-model="form.cost" type="number">
                        <template #append>元</template>
                    </el-input>
                    <el-alert type="info" :closable="false" style="background-color:#fff;padding:0;line-height: 24px;">
                        <p>价格必须是0-999999之间的数字，此价格为商户对所销售的商品的实际成本价进行备注记录，非必填选项，不会在前台销售页面中显示</p>
                    </el-alert>
                </div>
            </el-form-item>
            <el-form-item label="折扣" prop="desc">
                <div class="mt-4">
                    <el-input v-model="form.discount" type="number">
                        <template #append>折</template>
                    </el-input>
                    <el-alert type="info" :closable="false" style="background-color:#fff;padding:0;line-height: 24px;">
                        <p>根据销售价与市场价比例自动生成不需要编辑</p>
                    </el-alert>
                </div>
            </el-form-item>
            <el-form-item label="商品库存" prop="desc">
                <div class="mt-4">
                    <el-input v-model="form.inventory" type="number">
                        <template #append>元</template>
                    </el-input>
                    <el-alert type="info" :closable="false" style="background-color:#fff;padding:0;line-height: 24px;">
                        <p>库存必须是0-999999之间的整数</p>
                        <p>若启动了库存配置，则系统自动计算商品的总数，此处无需卖家填写</p>
                    </el-alert>
                </div>
            </el-form-item>
            <el-form-item label="商品货号" prop="desc">
                <div class="mt-4">
                    <el-input v-model="form.articleNo" type="number">
                    </el-input>
                    <el-alert type="info" :closable="false" style="background-color:#fff;padding:0;line-height: 24px;">
                        <p>商品货号是商家管理商品的编号，买家不可见</p>
                        <p>最多输入20个字符，只支持输入中文、字母、数字、_、/、-和小数点</p>
                    </el-alert>
                </div>
            </el-form-item>
            <el-form-item label="商品主图">
                <el-upload class="avatar-uploader" action="http://localhost:3003/upload/goods" :show-file-list="false"
                    :headers="headers" accept=".jpeg,.png,.jpg" :on-success="handleAvatarSuccess"
                    :on-error="handleUploadError" :before-upload="handleBeforeUpload" :on-remove="handleRemove">
                    <img v-if="form.img_lg" :src="form.img_lg" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
                <el-alert type="info" :closable="false" style="background-color:#fff;padding:0;line-height: 24px;">
                    <p>上传商品默认主图，如多规格时将默认图片或分规格上传规格主图，支持jpg、if、png格式上传或从图片空间选中，建议使用尺寸
                        800*800像素以上，大小不超过1M的正方形图片，上传后的图片将自动保存在图片空间的默认分类中</p>
                </el-alert>
            </el-form-item>
            <el-form-item label="商品轮播图">
                <el-upload v-model:file-list="file_list" action="http://localhost:3003/upload/slider"
                    list-type="picture-card" :headers="headers" accept=".jpeg,.png,.jpg"
                    :on-success="handlesliderSuccess" :on-error="handleUploadError">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
                <el-alert type="info" :closable="false" style="background-color:#fff; padding:0; line-height: 24px;">
                    <p>上传商品默认主图，如多规格时将默认图片或分规格上传规格主图，支持jpg、if、png格式上传或从图片空间选中，
                        建议使用尺寸 800*800像素以上，大小不超过1M的正方形图片，上传后的图片将自动保存在图片空间的默认分类中</p>
                </el-alert>
            </el-form-item>
        </el-form>
        <el-card shadow="none">
            <template #header>
                <div class="card-header">
                    <span>商品详情描述</span>
                </div>
            </template>
            <el-form label-width="100px">
                <el-form-item label="商品品牌" prop="desc">
                    <div class="mt-4">
                        <el-input v-model="form.brand">
                        </el-input>
                    </div>
                </el-form-item>
                <el-form-item label="商品描述" prop="desc">
                    <div style="border: 1px solid #ccc">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                            :defaultConfig="toolbarConfig" :mode="mode" />
                        <Editor style="height: 500px; overflow-y: hidden;" v-model="form.detail"
                            :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                    </div>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card shadow="none">
            <template #header>
                <div class="card-header">
                    <span>商品物流信息</span>
                </div>
            </template>
            <el-form label-width="100px">
                <el-form-item label="所在地" prop="desc">
                    <el-space>
                        <el-select v-model="position.provinceForm" @change="handleAddressChange" placeholder="请选择省份">
                            <el-option v-for="(item,index) in provinceForm" :key="item._id" :label="item.name"
                                :value="item.province_id" />
                        </el-select>
                        <el-select v-model="position.cityForm" @change="handleAddressChange(position.cityForm,1)"
                            placeholder="请选择城市">
                            <el-option v-for="(item,index) in cityForm" :key="item._id" :label="item.name"
                                :value="item.city_id" />
                        </el-select>
                        <el-select v-model="position.countyForm" @change="handleAddressChange(position.countyForm,2)"
                            placeholder="请选择县区">
                            <el-option v-for="(item,index) in countyForm" :key="item._id" :label="item.name"
                                :value="item.county_id" />
                        </el-select>
                        <el-select v-model="position.townForm" placeholder="请选择街道">
                            <el-option v-for="(item,index) in townForm" :key="item._id" :label="item.name"
                                :value="item.town_id" />
                        </el-select>
                    </el-space>
                </el-form-item>
                <el-form-item label="运费" prop="desc">
                    <div class="mt-4">
                        <el-input v-model="form.discount">
                            <template #append>元</template>
                        </el-input>
                    </div>
                </el-form-item>

            </el-form>
        </el-card>
    </el-card>
    <el-button @click="handleSubmit">提交</el-button>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, watchEffect } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useRoute,useRouter } from 'vue-router';
import address from '@/api/address'
import category from '@/api/category'
import goods from '@/api/goods'

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
let mode = ref('simple');
// 内容 HTML
const valueHtml = ref('')

// 模拟 ajax 异步获取内容
const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...', MENU_CONF: {} }
//上传图片配置
editorConfig.MENU_CONF['uploadImage'] = {
    // form-data fieldName ，默认值 'wangeditor-uploaded-image'
    fieldName: 'file',
    server: 'http://localhost:3003/upload/editor/',
    //自定义http header
    headers: {
        Authorization: `Bearer ${sessionStorage.token}`,
    }
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
let position = ref({});
let form = ref({});
let route = useRoute();
let router = useRouter();
//存储轮播图
let file_list = ref([]);
let loadList = async () => {
    let { status, msg, data } = await goods.detail({ id: route.params.id })
    if (status) {
        form.value = { ...data }
        file_list.value = data.slider.split(',').map(item => {
            return {
                name: item,
                url: item
            }
        });
        console.log({ ...data });
        console.log(file_list.value);
    }
}
loadList();
// 添加token
let token = sessionStorage.token;
let headers = { Authorization: `Bearer ${token}` };

const handlesliderSuccess = ({ status, msg }, uploadFile) => {
    //如果上传成功
    if (status) {
        // form.avatar = URL.createObjectURL(uploadFile.raw);
        ElMessage.success(msg);
    } else {
        ElMessage.error(msg);
    }
}
// 上传失败
let handleUploadError = (error, uploadFile) => {
    let { status, msg } = JSON.parse(error.message);
    ElMessage.error(msg);
}
const handleBeforeUpload = (rawFile) => {
    let isValid = /^image\/(jpeg|png|jpg)$/.test(rawFile.type);
    if (!isValid) {
        ElMessage.error('头像必须是jpg/png格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('头像体积不能大于2MB!')
        return false
    }
    return true
}
const handleAvatarSuccess = ({ status, msg, lgImg, mdImg }, uploadFile) => {
    //如果上传成功
    if (status) {
        // 生成图片的地址
        form.value.img_md = mdImg;
        form.value.img_lg = lgImg;
        // form.avatar = URL.createObjectURL(uploadFile.raw);
        ElMessage.success(msg);
    } else {
        ElMessage.error(msg);
    }
}
let cate_1st = ref([]);
let cate_2nd = ref([]);
let cate_3rd = ref([]);
// 请求子级
let loadInfo = async (pId) => {
    let { status, data } = await category.list({ pId });
    if (status) {
        return data;
    }
};
let handleCateChange = async (value, i = 0) => {
    switch (i) {
        case 0:
            // 请求二级分类
            cate_2nd.value = await loadInfo(value)
            //默认选中二级分类的第一项
            form.value.cate_2nd = cate_2nd.value[0] == undefined ? null : cate_2nd.value[0].id;
            if (cate_2nd.value[0]) {
                cate_3rd.value = await loadInfo(cate_2nd.value[0].id);
                form.value.cate_3rd = cate_3rd.value[0] == undefined ? null : cate_3rd.value[0].id;
            }
            break;
        case 1:
            cate_3rd.value = await loadInfo(value);
            form.value.cate_3rd = cate_3rd.value[0] == undefined ? null : cate_3rd.value[0].id;
            break;
        default: break;
    }
}
let provinceForm = ref([]);
let cityForm = ref([]);
let countyForm = ref([]);
let townForm = ref([]);
let address_1 = async () => {
    let { status, msg, data } = await address.province();
    if (status) {
        return data;
    }
}
let address_2 = async (id) => {
    let { status, msg, data } = await address.city({ id });
    if (status) {
        return data;
    }
}
let address_3 = async (id) => {
    let { status, msg, data } = await address.county({ id });
    if (status) {
        return data;
    }
}
let address_4 = async (id) => {
    let { status, msg, data } = await address.town({ id });
    if (status) {
        return data;
    }
}
let handleAddressChange = async (value, i = 0) => {
    switch (i) {
        case 0:
            // 请求二级分类
            cityForm.value = await address_2(value)
            //默认选中二级分类的第一项
            position.value.cityForm = cityForm.value[0].city_id
            countyForm.value = await address_3(cityForm.value[0].city_id);
            position.value.countyForm = countyForm.value[0].county_id
            townForm.value = await address_4(countyForm.value[0].county_id);
            position.value.townForm = townForm.value[0] == undefined ? null : townForm.value[0].town_id;
            break;
        case 1:
            // 请求三级分类
            countyForm.value = await address_3(value)
            //默认选中二级分类的第一项
            position.value.countyForm = countyForm.value[0].county_id
            townForm.value = await address_4(countyForm.value[0].county_id);
            position.value.townForm = townForm.value[0] == undefined ? null : townForm.value[0].town_id;
            break;
        case 2:
            // 请求四级分类
            townForm.value = await address_4(value)
            //默认选中二级分类的第一项
            position.value.townForm = townForm.value[0].town_id
            break;
        default: break;
    }
}
watchEffect(async () => {
    try {
        provinceForm.value = await address_1();
        cate_1st.value = await loadInfo(1);
        cate_2nd.value = await loadInfo(form.value.cate_1st);
        cate_3rd.value = await loadInfo(form.value.cate_2nd);
    }
    catch (error) {
    }
})

let handleSubmit = async () => {
    let a = [];
    file_list.value.forEach((item) => {
        if(item.response){
            a.push(item.response.src);
        }else{
            a.push(item.url);
        }
        
    });
    form.value.slider = a.toString()
    console.log(form.value);
    let { status, msg } = await goods.alter(route.params.id, { ...form.value });
    if (status) {
        router.push('/goods/list')
        ElMessage.success(msg);
    } else {
        ElMessage.error(msg);
    }
}
</script>
<style scoped>
.editor-box {
    border: 1px solid #ccc;
    border-radius: 3px;
}

.el-input {
    width: 200px;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>